﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Diagnostics;
using System.Windows.Forms;


namespace VSProcess
{
    [RunInstaller(true)]
    public partial class VSProcessDetector : Installer
    {
        public VSProcessDetector()
        {
            InitializeComponent();
        }

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            while (DevEnvRunning())
            {
                DialogResult result = MessageBox.Show("Setup has detected that Visual Studio is currently running.  Please close Visual Studio to continue or click Cancel to exit setup.",
                    "VSTime Setup", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    

                if (result == DialogResult.Cancel)
                {
                    throw new InstallException("User cancelled setup");
                }
            }
        }

        private bool DevEnvRunning()
        {
            bool _devenvRunning = false;
            Process[] processes = Process.GetProcesses();
            foreach (Process p in processes)
            {
                if (p.ProcessName.Contains("devenv"))
                {
                    _devenvRunning = true;
                }
            }
            return _devenvRunning;
        }
    }
}
